<?php

class TextManager
{
	static private $sInstance;
	private $oLang;
	private $oTextTable;
	
	private function __construct()
	{
		$accessLocales = array("ru");
		
		// Определяем локализацию
		if (Input::hasRequest("lang"))
			$this->oLang = Input::request("lang");
		else if (Input::hasCookie("lang"))
			$this->oLang = Input::cookie("lang");
		else
			$this->oLang = DEF_LANG;
		
		if (array_search($this->oLang, $accessLocales) === false)
			$this->oLang = DEF_LANG;
			
		require_once $_SERVER["DOCUMENT_ROOT"] . "/private/locale/" . $this->oLang . ".php";
		$this->oTextTable = &$_textTable;
	}
	
	private function __clone() {}
	
	public static function &i()
	{
		if (is_null(self::$sInstance) || !is_object(self::$sInstance))
			self::$sInstance = new self();
		
		return self::$sInstance;
	}
	
	/** Ищет и возвращает строку локализации */
	public static function tr($text, $echo = true)
	{
		return self::i()->text($text, $echo);
	} 
	
	public function lang()
	{
		return $this->oLang;
	}
	
	/** Ищет и возвращает строку локализации */
	public function text($text, $echo = true)
	{
		if (strpos($text, "~~~") === 0)
		{
			$text = substr($text, 3);
			$lang = $this->lang();
			for ($i = 0; $i < 2; ++$i)
			{
				$matches = array();
				if (preg_match(sprintf("/\[%s:\](.*)\[:%s\]/i", $lang, $lang), $text, $matches) === 1)
				{
					$text = $matches[1];
					break;
				}
				
				$lang = DEF_LANG;
			}
		}
		else 
		{
			$key = strtoupper($text);
			if (isset($this->oTextTable[$key]))
				$text = $this->oTextTable[$key];
		}
		
		if (!$echo)
			return $text;
		echo $text;
		return null;
	}
	
	public function langs($text)
	{
		if (strpos($text, "~~~") !== 0)
			return array();
		
		$text = substr($text, 3);
		$matches = null;
		preg_match_all("/\[([a-z]+):\]/i", $text, $matches);
		
		$langs = array();
		foreach ($matches as $match)
		{
			$langs[] = $match[1];
		}
		return $match;
	}
}

?>